from web_serve_easy.application import utils


def parse(recv_data):
    loc = recv_data.find('\r\n')
    request_line = recv_data[:loc]
    request_line_list = request_line.split(' ')
    request_path = request_line_list[1]
    return request_path

def application(new_socket, ip_port):

    recv_data = new_socket.recv(1024).decode()
    if not recv_data:
        print("%s已下线" % str(ip_port))
        new_socket.close()
        return

    request_path = parse(recv_data)

    if (request_path == '/'):
        request_path = 'index.html'
   
    try:
        with open("static/"+request_path, 'rb') as file:
            response_body = file.read()
            response = utils.create_response('HTTP/1.1 200 OK\r\n', response_body)
    except Exception as e:
        response_body = ("%s" %e).encode()
        response = utils.create_response('HTTP/1.1 404 NOT FOUND\r\n', response_body)


    new_socket.send(response) 